<template>
  <div>
    <p>Here is the data: {{ fromApi }}</p>
    other {{ other }}
  </div>
</template>

<script>
import { defineComponent, toRefs, reactive } from 'vue'
import { onBeforeRouteUpdate } from 'vue-router'

function delay (timeout, result) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve(result)
    }, timeout)
  })
}

export default defineComponent({
  name: 'ComponentWithData',
  setup () {
    const data = reactive({other: 'old', fromApi: null})
    onBeforeRouteUpdate(async (to, from, next) => {
      console.info('this in onBeforeRouteUpdate', from, to)
      data.fromApi = await delay(100)
      next()
    })
    return {
      ...toRefs(data),
    }
  },
  async beforeRouteEnter (to, from, next) {
    console.info('this in beforeRouteEnter', this)
    await delay(300)
    next(vm => {
      console.log('got vm', vm)
      vm.other = 'Hola'
    })
  },
  beforeRouteLeave (to, from, next) {
    console.info('this in beforeRouteLeave', this)
    delay(300)
    next(vm => {
      console.log('got vm', vm)
      vm.other = 'Hola'
    })
  },
})
</script>
